<template>
    <div class="app-container">
        <div class="table-wrapper">
            <h4>道路路基路面震害因子量化取值表</h4>
            <div class="buttonGroup">
                <el-button type="primary" @click="handleBrickBatchDelete">删除</el-button>
            </div>
            <div class="table-contain">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
                    :span-method="mergeRowMethod" :row-class-name="tableRowClassName">
                    <el-table-column type="selection" />
                    <!-- <el-table-column type="index" label="序号" width="80" /> -->
                    <el-table-column prop="serialNumber" header-align="center" align="center" label="序号" width="80">
                        <template #default="scope">
                            <el-input v-if="scope.row.isEdit && scope.row.isNew" v-model="scope.row.serialNumber"
                                size="small"></el-input>
                            <span v-else>{{ scope.row.serialNumber }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="damageFactor" header-align="center" align="center" label="震害因子">
                        <template #default="scope">
                            <span v-if="!scope.row.isEdit">{{ scope.row.damageFactor }}</span>
                            <el-input v-else v-model="scope.row.damageFactor" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="category" header-align="center" align="center" label="类别">
                        <template #default="scope">
                            <span v-if="!scope.row.isEdit">{{ scope.row.category }}</span>
                            <el-input v-else v-model="scope.row.category" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantizedValue" header-align="center" align="center" label="震害因子量化值">
                        <template #default="scope">
                            <span v-if="!scope.row.isEdit">{{
                                scope.row.quantizedValue ? Number(scope.row.quantizedValue).toFixed(2) : '' }}</span>
                            <el-input v-else v-model="scope.row.quantizedValue" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="120">
                        <template #default="scope">
                            <el-button type="text" size="small" @click="handleBrickModify(scope.$index, scope.row)">
                                {{ scope.row.isEdit ? '应用' : '修改' }}
                            </el-button>
                            <el-button type="text" size="small"
                                @click="handleBrickDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button class="add" style="width: 100%" @click="handleBrickAdd()">
                    <el-icon style="vertical-align: middle">
                        <Plus />
                    </el-icon>
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 获取当前实例
const { proxy } = getCurrentInstance();
// 引入接口
import { getAllRdFactor, saveOrUpdateRdFactor, deleteRdFactorById } from "@/api/vulnerModelManagement/roadCalParameterMaintenance.js";
// 表格
const multipleSelection = ref([]);
const tableData = ref([]);

//修改 保存
const handleBrickModify = (index, row) => {
    if (row.isEdit) { // 编辑状态点击时，代表保存
        let isValid = true; // 用于标记所有输入是否有效
        for (const key in row) {
            if (Object.hasOwnProperty.call(row, key)) {
                if (key !== 'isEdit' && key !== 'isNew'&& key!=='crdfColumn' && key!=='serialData' && key!=='createUser') {
                    const element = row[key];
                    if (element === '' || element === null) {
                        ElMessage({
                            type: 'warning',
                            message: '请填写数据!'
                        });
                        isValid = false;
                        break; // 一旦发现无效数据，立即退出循环
                    }
                    if(key === 'quantizedValue'){
                        if (!/^(-?\d+(\.\d+)?)$/.test(element)) {
                            ElMessage({
                                type: 'warning',
                                message: '震害因子量化值请输入有效的数值!'
                            });
                            isValid = false;
                            break; // 一旦发现无效数据，立即退出循环
                        }
                    }
                }
            }
        }
        if (isValid) {
        onAddOrUpdateRows(row)
        }
    } else {
        row.isEdit = true
    }
}
// 表格选择事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
// 表格行状态
const tableRowClassName = ({ row, rowIndex }) => {
    if (row.defaultData == '1') {
        return 'add-row';
    } else {
        return '';
    }
}
//删除单行
const handleBrickDelete = (index, row) => {
    //删除
    ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        //tableData.value.splice(index, 1)
        await onDeleteRows(row.crdfId)
        onSearch()
    }).catch((error) => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}
//删除多行
const handleBrickBatchDelete = () => {
    //删除
    ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        //multipleSelection.value[0].cddrId.join(',')
        let ids = []
        multipleSelection.value.forEach(item => { ids = ids.concat(item.crdfId) })
        await onDeleteRows(ids.join(','))
        onSearch()
    }).catch((error) => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}
//新增行事件
const handleBrickAdd = async () => {
    const newObj = { isEdit: true, isNew: true, rowNum: 1, serialNumber: '', damageFactor: '', category: '', quantizedValue: '' }
    tableData.value.push(newObj)
}
// 合并行
const mergeRowMethod = ({ row, column, rowIndex, columnIndex }) => {
    // columnIndex 代表列数，从0开始计数,我们要合并的字段属于第一,二列，取0，1
    if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        return {
            rowspan: row.rowNum, // 待合并行数 -- 合并的行数长度就等于之前赋值的子数据的长度；未赋值的即表示0，不显示
            colspan: 1  // 待合并列数 -- 合并的列数自身占一列，被合并的要返回0，表示不显示
        };
    }
}

//查询
const onSearch = () => {
    // 道路路基路面震害因子量化取值表表查询
    getAllRdFactor().then((res) => {
        if (res.code === 200) {
            console.log(res)

            tableData.value = [];
            // const rows = res.data.rows;
            const data = res.data
            for (const key in data) {
                if (Object.hasOwnProperty.call(data, key)) {
                    const element = data[key];
                    // tableData.value.push(element.serialData);
                    if (element.serialData.length > 0) {
                        element.serialData[0].rowNum = element.serialData.length // 只赋值第一个元素跨的行数
                        tableData.value.push(...element.serialData);
                    }
                }
            }
        }
    }).catch(err => {
        console.log(err);
    });
}
//道路路基路面震害因子量化取值表添加行  新增行或更新保存行，存在同名basicIntensity是更新，不存在是添加
const onAddOrUpdateRows = async (row) => {
    const paramsp = [
        {
            crdfId: row.crdfId,
            serialNumber: row.serialNumber,
            damageFactor: row.damageFactor,
            category: row.category,
            quantizedValue: row.quantizedValue,
        },
    ]
    await saveOrUpdateRdFactor(paramsp).then((res) => {
        if (res.code === 200) {
            row.isEdit = false
            row.isNew = false
            ElMessage({
                type: 'success',
                message: '保存成功!'
            });
        }
    }).catch(err => {
        console.log(err);
    });
    onSearch()
}
// 删除行
const onDeleteRows = async (ids) => {
    if (!ids || ids.length <= 0) {
        ElMessage({
            type: 'warning',
            message: '请选中数据!'
        });
        return
    }
    const paramsp = { rdFactorIds: ids }
    await deleteRdFactorById(paramsp).then((res) => {
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
        }
    }).catch(err => {
        ElMessage({
            type: 'error',
            message: '删除失败!'
        });
    })
}

// 挂载
onMounted(() => {
    onSearch()
});
</script>

<style lang="scss" scoped></style>